<template>
  <div class="map w1 h1" ref="map-ref" id="data-center-map"></div>
</template>
<script>
import { mapState, mapGetters, mapActions } from 'vuex'
import { idMapProvince, idMapCity } from '@/utils/mapConfig'
// import window.AMap from 'window.AMap'
import AMapLoad from '@/utils/AMapLoad'

import { getGeoJson } from '@/api'
import option from './option'
function findCityName(rname, code) {
  if (rname === 'ROLE_PROVINCE') {
    return idMapProvince.find(t => t.code === code).key
  } else {
    let startKey = code.substring(0, 2)
    if (!startKey) {
      return false
    }
    let whichProvince = idMapProvince.find(t => t.code.startsWith(startKey))
      .code
    return idMapCity[whichProvince].find(t => t.code == code).key
  }
}
export default {
  computed: {
    ...mapGetters(['userInfo']),
    ...mapState({
      companyList: state => {
        return state.cityInfo.companyList
      }
    })
  },
  mounted() {
    // this.initState();
    // const vm = this
    // const aMapScript = document.createElement('script')
    // aMapScript.setAttribute(
    //   'src',
    //   'https://webapi.amap.com/maps?v=1.4.12&key=507de00c91710cf81bb0e7a2cfc26263'
    // )
    // document.head.appendChild(aMapScript)
    // aMapScript.onload = function() {
    //   vm.init()
    // }
    AMapLoad().then(Amap => {
      this.init()
    })
  },
  beforeDestroy() {
    if (this.mapBottle) {
      window.addEventListener('resize', () => false)
    }
  },
  watch: {
    companyList: {
      handler() {
        this.init()
      }
    }
  },
  data() {
    return {
      mapBottle: null
    }
  },
  methods: {
    ...mapActions(['getSingleCity', 'logout']),
    initState() {
      const vm = this
      const { areaName, rname, areaCode } = vm.userInfo
      const companyList = vm.companyList || []
      const key = findCityName(rname, areaCode)
      getGeoJson(key).then(res => {
        if (res.code && !!res.data) {
          vm.echarts.registerMap(areaName, res.data)
          vm.$nextTick(() => {
            const dom = vm.$refs['map-ref']
            vm.mapBottle = vm.echarts.init(dom)
            let config = option
            config.series = []
            config.geo.map = areaName
            let seriesData = companyList.map(item => {
              return {
                name: item.name,
                value: [item.lng, item.lat, 40],
                symbolSize: 18,
                itemStyle: {
                  normal: {
                    color: item.state == 1 ? '#08ED74' : 'red'
                  }
                },
                tooltip: {
                  formatter: params => {
                    return `${params.marker} ${params.name}`
                  }
                }
              }
            })
            config.series.push({
              name: '企业名称',
              type: 'effectScatter',
              coordinateSystem: 'geo',
              data: seriesData,
              hoverAnimation: true,
              zlevel: 2,
              rippleEffect: {
                brushType: 'stroke'
              },
              label: {
                normal: {
                  formatter: '{b}',
                  position: 'right',
                  show: true
                }
              },
              showEffectOn: 'render'
            })
            vm.mapBottle.setOption(config)
            window.addEventListener('resize', () => {
              vm.mapBottle.resize()
            })
          })
        }
      })
    },

    init() {
      const vm = this
      const red_icon = new window.AMap.Icon({
        image:
          '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png',
        size: new window.AMap.Size(19, 32),
        imageSize: new window.AMap.Size(19, 32)
      })
      const blue_icon = new window.AMap.Icon({
        image:
          '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png',
        size: new window.AMap.Size(19, 32),
        imageSize: new window.AMap.Size(19, 32)
      })

      const { areaId, areaName, areaCode, rname } = vm.userInfo
      const companyList = this.companyList || []
      vm.defaultTitle = areaName
      const level = rname === 'ROLE_PROVINCE' ? 'province' : 'city'
      const infoWindow = new window.AMap.InfoWindow({
        offset: new window.AMap.Pixel(0, -30)
      })
      window.AMap.plugin(['AMap.DistrictSearch'], function() {
        const district = new window.AMap.DistrictSearch({
          subdistrict: 0, //返回下一级行政区
          level,
          showbiz: false,
          extensions: 'all' //返回行政区边界坐标组等具体信息
        }).search(areaName, function(status, result) {
          result = result.districtList[0]
          let bounds = result.boundaries
          vm.mapBottle = new window.AMap.Map('data-center-map', {
            mapStyle: 'amap://styles/8424aa3d2c0d37b84f433d36eb8252af',
            center: result.center,
            pitch: 52,
            viewMode: '3D', //开启3D视图,默认为关闭
            labelzIndex: 130,
            cursor: 'pointer',
            skyColor: '#fff',
            isHotspot: false
          })

          // AMapUI.loadUI(["overlay/SimpleMarker"], function(SimpleMarker) {
          //   beginInitPoint(SimpleMarker)
          // })

          // function beginInitPoint(SimpleMarker) {
          //   companyList.forEach(t => {
          //     let marker = new SimpleMarker({
          //       iconTheme: "default",
          //       //使用内置的iconStyle
          //       iconStyle: t.state === 1 ? "green" : "red",
          //       position: new window.AMap.LngLat(t.lng, t.lat),
          //       map: vm.mapBottle,
          //       title: t.address + t.name
          //     })
          //   })
          // }
          // 1=正常，2=预警，3=告警，4-故障
          companyList.forEach(t => {
            let marker = new window.AMap.Marker({
              map: vm.mapBottle,
              icon: t.state === 1 ? blue_icon : red_icon,
              position: new window.AMap.LngLat(t.lng, t.lat),
              title: t.address + t.name
            })
            marker.setMap(vm.mapBottle)
            marker.on('mouseover', e => {
              let htmlText = `<div>
                <span>企业名称：</span><span>${t.name}</span><br/>
                <span>地址：</span><span>${t.address}</span><br/>
                <span>联系人：</span><span>${t.contactName}</span><br/>
                <span>联系电话：</span><span>${t.contactPhone}</span>
              </div>`
              infoWindow.setContent(htmlText)
              infoWindow.open(vm.mapBottle, e.target.getPosition())
            })
          })

          vm.mapBottle.on('complete', () => {
            let object3Dlayer = new window.AMap.Object3DLayer({ zIndex: 1 })
            vm.mapBottle.add(object3Dlayer)
            //利用行政区查询获取边界
            let district = new window.AMap.DistrictSearch({
              subdistrict: 0,
              extensions: 'all',
              level
            })
            district.search(areaName, function(status, result) {
              var bounds = result.districtList[0].boundaries
              var height = 30000
              var color = 'rgb(137, 207, 240)' //rgba
              var wall = new window.AMap.Object3D.Wall({
                path: bounds,
                height: height,
                color: color
              })
              wall.backOrFront = 'both'
              wall.transparent = true
              object3Dlayer.add(wall)
            })
          })

          vm.mapBottle.on('click', () => {
            infoWindow.close()
          })
        })
      })
    }
  }
}
</script>
